package com.example.tool.window;

import com.intellij.icons.AllIcons;
import com.intellij.ui.JBColor;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.table.JBTable;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

public class HToolWindowPage {
  private final JPanel jPanel;
  private final JBTable jbTable;
  private final JTextField filterText;

  public JPanel getjPanel() {
    return jPanel;
  }

  public JTextField getFilterText() {
    return filterText;
  }

  public JBTable getJbTable() {
    return jbTable;
  }

  /**
   * 创建表格组件
   * @param columns 表格列
   * @param rows    表格行数据
   * @return 表格对象
   */
  public static JBTable crateTable(List<String> columns, List<List<Object>> rows) {
    JBTable jbTable = new JBTable();
    DefaultTableModel defaultTableModel = new DefaultTableModel() {
      @Override
      public Class<?> getColumnClass(int columnIndex) {
        if (columnIndex == 0) {
          return Boolean.class;
        }
        return super.getColumnClass(columnIndex);
      }

      @Override
      public boolean isCellEditable(int row, int column) {
        return column == 0;
      }
    };
    jbTable.addMouseListener(new MouseAdapter() {
      @Override
      public void mouseClicked(MouseEvent e) {
        int column = jbTable.columnAtPoint(e.getPoint());
        if (column != 0) {
          int row = jbTable.rowAtPoint(e.getPoint());
          if (row >= 0) {
            boolean currentValue = (Boolean) jbTable.getValueAt(row, 0);
            jbTable.setValueAt(!currentValue, row, 0);
          }
        }
      }
    });
    defaultTableModel.addColumn("");
    if (columns != null) {
      for (String column : columns) {
        defaultTableModel.addColumn(column);
      }
    }
    if (rows != null) {
      for (List<Object> row : rows) {
        Object[] objectArrayWithFalse = row.toArray(new Object[0]);
        defaultTableModel.addRow(objectArrayWithFalse);
      }
    }
    int columnCount = defaultTableModel.getColumnCount();
    jbTable.setModel(defaultTableModel);
    for (int i = 0; i < columnCount; i++) {
      TableColumn column = jbTable.getColumnModel().getColumn(i);
      if (i == 0) {
        column.setMaxWidth(30);
        column.setMinWidth(30);
      }
      column.setCellRenderer(new HToolWindowRenderer());
    }
    jbTable.setRowHeight(30);
    JTableHeader tableHeader = jbTable.getTableHeader();
    tableHeader.setReorderingAllowed(false);
    tableHeader.setDefaultRenderer(new HToolWindowRenderer(JBColor.RED));

    // 表格只能单选
    jbTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    // 隐藏第一列
    jbTable.removeColumn(jbTable.getColumnModel().getColumn(1));
    return jbTable;
  }

  /**
   * 初始化页面
   * @param jbTable    表格对象
   * @param screenText 表格筛选文本文字
   */
  public HToolWindowPage(JBTable jbTable, String screenText) {
    jPanel = new JPanel();
    jPanel.setLayout(new BorderLayout());
    JBScrollPane jbScrollPane = new JBScrollPane(jbTable);
    TableRowSorter<TableModel> sorter = new TableRowSorter<>(jbTable.getModel());
    jbTable.setRowSorter(sorter);
    // 禁用表头点击排序
    for (int i = 0; i < jbTable.getColumnCount(); i++) {
      sorter.setSortable(i, false);
    }
    filterText = getjTextField();
    filterText.addActionListener(e -> filterButtonActionPerformed(jbTable, filterText, sorter));
    JButton filterButton = getjButton();
    filterButton.addActionListener(e -> filterButtonActionPerformed(jbTable, filterText, sorter));
    JPanel panel = new JPanel(new BorderLayout());
    panel.setBorder(JBUI.Borders.empty(10));
    panel.add(new JLabel(screenText), BorderLayout.WEST);
    panel.add(filterText, BorderLayout.CENTER);
    panel.add(filterButton, BorderLayout.EAST);
    jPanel.add(panel, BorderLayout.NORTH);
    // 添加表格
    jPanel.add(jbScrollPane, BorderLayout.CENTER);
    this.jbTable = jbTable;
  }

  /**
   * 创建筛选按钮
   * @return 筛选按钮
   */
  @NotNull
  private static JButton getjButton() {
    JButton filterButton = new JButton();
    filterButton.setIcon(AllIcons.Actions.Find);
    filterButton.setPreferredSize(new Dimension(30, 30));
    filterButton.setOpaque(false);
    filterButton.setContentAreaFilled(false);
    filterButton.setBorderPainted(false);
    filterButton.setFocusPainted(false);
    return filterButton;
  }

  /**
   * 创建筛选文本框
   * @return 筛选文本框
   */
  @NotNull
  private static JTextField getjTextField() {
    JTextField filterText = new JTextField();
    Border innerBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, JBColor.BLACK);
    Border outerBorder = JBUI.Borders.empty(5);
    filterText.setBorder(new CompoundBorder(outerBorder, innerBorder));
    return filterText;
  }

  /**
   * 表格筛选
   * @param jbTable    表格对象
   * @param filterText 文本输入框
   * @param sorter     筛选对象
   */
  private void filterButtonActionPerformed(JBTable jbTable, JTextField filterText, TableRowSorter<TableModel> sorter) {
    // 清除表格中所有选中行
    jbTable.clearSelection();
    String text = filterText.getText();
    if (text.isEmpty()) {
      sorter.setRowFilter(null);
    } else {
      int columnCount = jbTable.getColumnCount();
      int[] indices = new int[columnCount - 1];
      for (int i = 1; i < columnCount; i++) {
        indices[i - 1] = i;
      }
      sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text, indices));
    }
  }
}
